/*
 * 分类弹窗
 * 功能：显示子分类
 */

(function(factory){
    if(typeof define === 'function' && define.amd){
        define(['jquery','../../../Common/catedb'],factory);
    }else{
        factory(window.jQuery);
    }
}(function($){
    /*省市县=====================================*/
    $.fn.areaE = function(o) {
        var that = $.extend({},$.fn.areaE.defaults, o);
        return this.each(function() {
            var t = $(this);
            var timer=null;
            var currentPageLoad = {"isLoad": true};
            
            //只显示中国================
            //var ThatData=LocalData[that.name][0][1].child;
            //显示全部
            var ThatData=LocalData[that.name][0];
            var tdataB=[],tdataC=[],tdataD=[];
            var wrap=null;
            var arthtml=$('<div class="dl-city-m">'
                            + '<div class="mc province_item" data-area="0"></div>'
                            + '<div class="mc city_item" data-area="1"></div>'
                            + '<div class="mc area_item" data-area="2"></div>'
                            + '<div class="mc town_item" data-area="3"></div><div class="fc"></div>'
                           +'</div>');
                
            t.off('click').on('click',function(){
				t.addClass('focus');
                $(arthtml).remove();
                
                var top=t.offset().top,left=t.offset().left,height=t.outerHeight(),width=t.outerWidth();
                arthtml.css({position:'absolute',display:'block',padding:0,left:left+'px',top:(top+height-1)+'px',visibility:'hidden',opacity:0,'z-index':1000});
                                
                $('body').append(arthtml);
                
                
                wrap=$(arthtml);
                var province=wrap.find("."+that.a+"_item"),
                city=wrap.find("."+that.b+"_item"),
                area=wrap.find("." + that.c + "_item"),
                town=wrap.find("." + that.d + "_item"),
                con=wrap.find(".mc");
                con.hide();

                function gethtml(z, result){
                    $(z).html('');
                    var html = [];
                    if($(z).data('area')>0){
                        html.push('<a href="javascript:;" class="back"><span>&lt;&lt;</span>返回</a>');
                    }
                    var longhtml = [];
                    var longerhtml = [];
                    for(var i in result){
                        result[i].short = result[i].short.replace(" ", "");
                        if (result[i].short.length > 12) {
                            longerhtml.push('<a href="javascript:;" class="longer-area" data-cid="'+result[i].area_code+'" data-path="'+result[i].area_code+'">'+result[i].short+'</a>');
                        } else if (result[i].short.length > 4) {
                            longhtml.push('<a href="javascript:;" class="long-area" data-cid="'+result[i].area_code+'" data-path="'+result[i].area_code+'">'+result[i].short+'</a>');
                        } else {
                            html.push('<a href="javascript:;" data-cid="'+result[i].area_code+'" data-path="'+result[i].area_code+'">'+result[i].short+'</a>');
                        }
                    }
                    html.push(longhtml.join(""));
                    html.push(longerhtml.join(""));

                    $(z).show().html(html.join(""));
                }
                //一级数据
                gethtml(province,ThatData);

                var ww=$(window).width();
                if(left+arthtml.width()>ww){
                    left=left+width-arthtml.width();                    
                }
                arthtml.css({left:left+'px',visibility:'visible',opacity:1});
                //arthtml.show();
                
                var areaname=[];
                province.delegate("a", "click", function(){
                    currentPageLoad.isLoad = false;
                    resetBindMouseEvent();
                    areaname=[$(this).text()];
                    selects(this,0);
                    var id=$(this).data('cid');

                    tdataB=ThatData[id].child;
                    if(typeof(tdataB)=='object'){
                        con.hide();
                        gethtml(city,tdataB);
                    }else{
						t.removeClass('focus');
					}
                });
                city.delegate("a:not(.back)", "click", function(){
                    areaname[1]=$(this).text();
                    delete areaname[2];
                    selects(this,1);
                    var id=$(this).data('cid');

                    tdataC=tdataB[id].child;
                    if(typeof(tdataC)=='object'){
                        con.hide();
                        gethtml(area,tdataC);
                    }else{
						t.removeClass('focus');
					}
                });
                area.delegate("a:not(.back)", "click", function(){                                        
                    areaname[2]=$(this).text();
                    delete areaname[3];
                    selects(this,2);
                    var id=$(this).data('cid');

                    tdataD=tdataC[id].child;
                    if(typeof(tdataD)=='object'){
                        con.hide();
                        gethtml(town,tdataD);
                    }else{
						t.removeClass('focus');
					}
                });
                town.delegate("a:not(.back)", "click", function(){
                    areaname[3]=$(this).text();
                    selects(this,3);
					t.removeClass('focus');
                });
                
                t.unbind("mouseenter").bind("mouseenter", function() {
                    
                }).unbind("mouseleave").bind("mouseleave", function() {
                    clearTimeout(timer);
                    timer = setTimeout(function(){ wrap.hide(); }, 200);
                    wrap.unbind("mouseenter").bind("mouseenter", function() {
                        clearTimeout(timer);
                    }).unbind("mouseleave").bind("mouseleave", function() {
                        wrap.hide();
						t.removeClass('focus');
                    });
                });
                
                
                var mouseEventChange = false;
                function resetBindMouseEvent() {
                    if (!mouseEventChange && !currentPageLoad.isLoad) {
                        mouseEventChange = true;
                        t.unbind("mouseleave");
                        t.unbind("mouseenter").bind("mouseenter", function() {
                            
                        });
                        wrap.unbind("mouseleave");
                        wrap.unbind("mouseenter").bind("mouseenter", function() {
                            wrap.show();
                        });
                    }
                }
                
                wrap.on('click','.back',function(){
                   var a=$(this).parent().data('area');
                   wrap.find('[data-area="'+(a-1)+'"]').show().siblings('.mc').hide();
                   if(a-1==0){
                       wrap.unbind("mouseleave").bind("mouseleave", function() {
                            wrap.hide();
                        });
                   }
                });
                function selects(item,s){
                    $(item).addClass('selected').siblings().removeClass('selected');

                    var name=[];
                    for(var i=0;i<areaname.length;i++){
                        if(areaname[i]){
                            name.push(areaname[i]);
                        }
                    }
                    var _item=[$(item).data('path'),name.join('-')];
                    var namestr=name.join('-');
                    if(namestr.length>that.cutstr) namestr = namestr.substring(0,that.cutstr)+'...';
                    t.html(namestr);
                    switch(s){
                        case 0:
                            if(that.type==0){
                                _return(_item);
                            }
                            break;
                        case 1:
                            if(that.type==0 || typeof(tdataB[$(item).data('cid')].child)=='undefined'){
                                _return(_item);
                            }
                            break;
                        case 2:
                            if(that.type==0 || typeof(tdataC[$(item).data('cid')].child)=='undefined'){
                                _return(_item);
                            }
                            break;
                        case 3:
                            _return(_item);
                            break;
                    }
                }
                
            });
            function _return(_item){
                var namestr = '';
                var show_namestr = '';
                var pathstr = '';

                namestr = show_namestr = _item[1];
                pathstr = _item[0];

                var namestr_len = namestr.length;
                if(namestr_len>that.cutstr) show_namestr = namestr.substring(0,that.cutstr)+'...';

                $(that.input).val(pathstr);

                if(show_namestr == ''){
                    show_namestr = that.default_val;
                }
                if($(t).is('input')){
                    $(t).val(show_namestr);
                }else{
                    $(t).html(show_namestr);
                }
                try{
                    wrap.remove();
                }catch(e){}                
                
                if($.isFunction(that.fn)){ that.fn(_item);}
            }
            initdb();
            function finditem(ids){
                if(!/[1-9][0-9]{5}/.test(ids)){
                    return false;
                }
                for(var i in ThatData){
                    if(ThatData[i].area_code==ids){
                        var item=ThatData[i];
                        var _item=[item.area_code,item.short];
                        _return(_item);
                        return;
                    }
                    var tdataB=ThatData[i].child;
                    for(var j in tdataB){
                        if(tdataB[j].area_code==ids){
                            var item=tdataB[j];
                            var _item=[item.area_code,ThatData[i].short+'-'+item.short];
                            _return(_item);
                            return;
                        }
                        var tdataC=tdataB[j].child;
                        for(var k in tdataC){
                            if(tdataC[k].area_code==ids){
                                var item=tdataC[k];
                                var _item=[item.area_code,ThatData[i].short+'-'+tdataB[j].short+'-'+item.short];
                                _return(_item);
                                return;
                            }
                            var tdataD=tdataC[k].child;
                            for(var l in tdataD){
                                if(tdataD[l].area_code==ids){
                                    var item=tdataD[l];
                                    var _item=[item.area_code,ThatData[i].short+'-'+tdataB[j].short+'-'+tdataC[k].short+'-'+item.short];
                                    _return(_item);
                                    return;
                                }
                            }
                        }
                    }
                }
            }
            /*初始化数据===============================*/
            function initdb(){
                var input=$(that.input).val();
                if(input != ''){
                    var vitem=input.split(",");
                    for(var i=0;i<vitem.length;i++){
                        finditem(vitem[i]);                            
                    }
                }
            };
        });
    };
    $.fn.areaE.defaults = {a:'province', b:'city', c:'area',d:'town',type:1};
}));